﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 替代料管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ItemsubstitutionsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Itemsubstitutions> _itemsubstitutionsRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public ItemsubstitutionsService(SqlSugarRepository<Itemsubstitutions> itemsubstitutionsRep, ISqlSugarClient sqlSugarClient)
    {
        _itemsubstitutionsRep = itemsubstitutionsRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询替代料管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询替代料管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ItemsubstitutionsOutput>> Page(PageItemsubstitutionsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _itemsubstitutionsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.PartNumId != null, u => u.PartNumId == input.PartNumId)
            .WhereIF(input.PartNumIds != null, u => u.PartNumIds == input.PartNumIds)
            .WhereIF(input.TicketsId != null, u => u.TicketsId == input.TicketsId)
            .WhereIF(input.StartTimeRange?.Length == 2, u => u.StartTime >= input.StartTimeRange[0] && u.StartTime <= input.StartTimeRange[1])
            .WhereIF(input.EndTimeRange?.Length == 2, u => u.EndTime >= input.EndTimeRange[0] && u.EndTime <= input.EndTimeRange[1])
            .LeftJoin<Partnum>((u, partNum) => u.PartNumId == partNum.Id)
            .LeftJoin<Partnum>((u, partNum, partNumIds) => u.PartNumIds == partNumIds.Id)
            .LeftJoin<tickets>((u, partNum, partNumIds, tickets) => u.TicketsId == tickets.Id)
            .Select((u, partNum, partNumIds, tickets) => new ItemsubstitutionsOutput
            {
                Id = u.Id,
                PartNumId = u.PartNumId,
                PartNumFkDisplayName = $"{partNum.PartNumCoding}-{partNum.PartNumName}-{partNum.SpeciFicationNumber}",
                PartNumIds = u.PartNumIds,
                PartNumIdsFkDisplayName = $"{partNumIds.PartNumCoding}-{partNumIds.PartNumName}-{partNumIds.SpeciFicationNumber}",
                TicketsId = u.TicketsId,
                TicketsFkDisplayName = $"{tickets.encode}-{tickets.ticketstype}",
                StartTime = u.StartTime,
                EndTime = u.EndTime,
                Remark = u.Remark,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取替代料管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取替代料管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Itemsubstitutions> Detail([FromQuery] QueryByIdItemsubstitutionsInput input)
    {
        return await _itemsubstitutionsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加替代料管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加替代料管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddItemsubstitutionsInput input)
    {
        var entity = input.Adapt<Itemsubstitutions>();
        return await _itemsubstitutionsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新替代料管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新替代料管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateItemsubstitutionsInput input)
    {
        var entity = input.Adapt<Itemsubstitutions>();
        await _itemsubstitutionsRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除替代料管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除替代料管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteItemsubstitutionsInput input)
    {
        var entity = await _itemsubstitutionsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _itemsubstitutionsRep.FakeDeleteAsync(entity);   //假删除
        //await _itemsubstitutionsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除替代料管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除替代料管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteItemsubstitutionsInput> input)
    {
        var exp = Expressionable.Create<Itemsubstitutions>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _itemsubstitutionsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _itemsubstitutionsRep.FakeDeleteAsync(list);   //假删除
        //return await _itemsubstitutionsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataItemsubstitutionsInput input)
    {
        var partNumIdData = await _itemsubstitutionsRep.Context.Queryable<Partnum>()
            .InnerJoinIF<Itemsubstitutions>(input.FromPage, (u, r) => u.Id == r.PartNumId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}"
            }).ToListAsync();
        var partNumIdsData = await _itemsubstitutionsRep.Context.Queryable<Partnum>()
            .InnerJoinIF<Itemsubstitutions>(input.FromPage, (u, r) => u.Id == r.PartNumIds)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}"
            }).ToListAsync();
        var ticketsIdData = await _itemsubstitutionsRep.Context.Queryable<tickets>()
            .InnerJoinIF<Itemsubstitutions>(input.FromPage, (u, r) => u.Id == r.TicketsId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.encode}-{u.ticketstype}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "partNumId", partNumIdData },
            { "partNumIds", partNumIdsData },
            { "ticketsId", ticketsIdData },
        };
    }
    
    /// <summary>
    /// 导出替代料管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出替代料管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageItemsubstitutionsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportItemsubstitutionsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "替代料管理导出记录");
    }
    
    /// <summary>
    /// 下载替代料管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载替代料管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportItemsubstitutionsOutput>(), "替代料管理导入模板", (_, info) =>
        {
            if (nameof(ExportItemsubstitutionsOutput.PartNumFkDisplayName) == info.Name) return _itemsubstitutionsRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}").Distinct().ToList();
            if (nameof(ExportItemsubstitutionsOutput.PartNumIdsFkDisplayName) == info.Name) return _itemsubstitutionsRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}").Distinct().ToList();
            if (nameof(ExportItemsubstitutionsOutput.TicketsFkDisplayName) == info.Name) return _itemsubstitutionsRep.Context.Queryable<tickets>().Select(u => $"{u.encode}-{u.ticketstype}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入替代料管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入替代料管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportItemsubstitutionsInput, Itemsubstitutions>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 源物料
                    var partNumIdLabelList = pageItems.Where(x => x.PartNumFkDisplayName != null).Select(x => x.PartNumFkDisplayName).Distinct().ToList();
                    if (partNumIdLabelList.Any()) {
                        var partNumIdLinkMap = _itemsubstitutionsRep.Context.Queryable<Partnum>().Where(u => partNumIdLabelList.Contains($"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}")).ToList().ToDictionary(u => $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PartNumId = partNumIdLinkMap.GetValueOrDefault(e.PartNumFkDisplayName ?? "");
                            if (e.PartNumId == null) e.Error = "源物料链接失败";
                        });
                    }
                    // 链接 替代物料
                    var partNumIdsLabelList = pageItems.Where(x => x.PartNumIdsFkDisplayName != null).Select(x => x.PartNumIdsFkDisplayName).Distinct().ToList();
                    if (partNumIdsLabelList.Any()) {
                        var partNumIdsLinkMap = _itemsubstitutionsRep.Context.Queryable<Partnum>().Where(u => partNumIdsLabelList.Contains($"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}")).ToList().ToDictionary(u => $"{u.PartNumCoding}-{u.PartNumName}-{u.SpeciFicationNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PartNumIds = partNumIdsLinkMap.GetValueOrDefault(e.PartNumIdsFkDisplayName ?? "");
                            if (e.PartNumIds == null) e.Error = "替代物料链接失败";
                        });
                    }
                    // 链接 工单
                    var ticketsIdLabelList = pageItems.Where(x => x.TicketsFkDisplayName != null).Select(x => x.TicketsFkDisplayName).Distinct().ToList();
                    if (ticketsIdLabelList.Any()) {
                        var ticketsIdLinkMap = _itemsubstitutionsRep.Context.Queryable<tickets>().Where(u => ticketsIdLabelList.Contains($"{u.encode}-{u.ticketstype}")).ToList().ToDictionary(u => $"{u.encode}-{u.ticketstype}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TicketsId = ticketsIdLinkMap.GetValueOrDefault(e.TicketsFkDisplayName ?? "");
                            if (e.TicketsId == null) e.Error = "工单链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Itemsubstitutions>>();
                    
                    var storageable = _itemsubstitutionsRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
